package com.whu.MenuHub.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.whu.MenuHub.domain.Food;
import com.whu.MenuHub.domain.User;
import com.whu.MenuHub.exception.MenuHubException;
import com.whu.MenuHub.service.UserService;
import com.whu.MenuHub.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/users")
@Api(tags = "用户信息管理API")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/id/{id}")
    @ApiOperation("根据id获取用户信息")
    @PreAuthorize("hasAnyAuthority('all',#id.toString())")
    public User getUserByID(@ApiParam("用户ID")@PathVariable Integer id){
        //把密码字段清空 确保安全
        User user=userService.getUserByUserID(id);
        if(user!=null)user.setPassword(null);
        return user;
    }

    @GetMapping("/username/{username}")
    @ApiOperation("根据username获取用户信息")
    @PreAuthorize("hasAnyAuthority('all', #username) ")
    public User getUserByUserName(@ApiParam("账户名") @PathVariable String username){
        User user=userService.getUserByUserName(username);
//        if(user!=null)user.setPassword(null);
        User user1=new User();
        user1.setId(user.getId());
        user1.setRole(user.getRole());
        user1.setLevel(user.getLevel());
        user1.setAvatar(user.getAvatar());
        user1.setUsername(username);
        user1.setGender(user.getGender());
        user1.setBirthday(user.getBirthday());
        user1.setNativeplace(user.getNativeplace());
        return user1;
    }

    @PostMapping("")
    @ApiOperation("新增一条用户记录")
    public User InsertUser(@ApiParam("用户信息")@RequestBody User user) throws MenuHubException {
        User resultUser=userService.insertUser(user);
        if(resultUser!=null)resultUser.setPassword(null);
        return user;
    }

    @PutMapping("")
    @ApiOperation("修改一条用户记录")
    @PreAuthorize("hasAnyAuthority(#user.id.toString())")
    public void updateUser(@ApiParam("用户信息")@RequestBody User user) throws MenuHubException {
        User user1=userService.getUserByUserName(user.getUsername());
        if(user1!=null&&user1.getId()!=user.getId()){
            throw new MenuHubException(MenuHubException.ErrorType.UPDATE_ERROR,"账号名已经存在，用户信息修改失败");
        }
        userService.updateUserByID(user,true);
    }
    @DeleteMapping("/{id}")
    @ApiOperation("删除一条用户记录")
    @PreAuthorize("hasAnyAuthority('all',#id.toString())")
    public void deleteUser(@ApiParam("用户ID")@PathVariable Integer id) throws MenuHubException {
        userService.deleteUserByID(id);
    }

    //根据条件查询用户，条件可以为空
    @ApiOperation("根据条件查询用户")
    @GetMapping("")
    @PreAuthorize("hasAnyAuthority('all')")
    public IPage<User> findUser(@ApiParam("用户名称")@RequestParam(value = "username",required = false) String username,
                                         @ApiParam("用户身份")@RequestParam(value = "Role",required = false) String Role,
                                         @ApiParam("用户等级") @RequestParam(value = "level",required = false)  Integer level,
                                         @ApiParam("页码")@RequestParam(defaultValue = "0")Integer pageNum,
                                         @ApiParam("每页记录数") @RequestParam(defaultValue = "10")Integer pageSize){
        Map<String,Object> condition=new HashMap<>();
        if(username!=null) {
            condition.put("username",username);
        }
        if(Role!=null) {
            condition.put("role",Role);
        }
        if(level!=null) {
            condition.put("level",level);
        }
        IPage<User> iPage=userService.findUsers(condition, pageNum,pageSize);
        // 获取数据列表
        List<User> userList = iPage.getRecords();
       // 使用for循环遍历数据列表
        for (User user : userList) {
            user.setPassword(null);
        }
        return iPage;
    }
    @GetMapping("/recentActive")
    @ApiOperation("获取近7日最活跃的用户信息")
    List<User> getRecentActive(){
        return userService.getRecentActiveUser();
    }
    @GetMapping("/historyActive")
    @ApiOperation("获取历史最活跃的用户信息")
    List<User> getHistoryActive(){
        return userService.getHistoryActiveUser();
    }
}
